import { constantRoutes } from '@/router'
import Layout from '@/layout'
import axios from 'axios'
import { getInfo } from '@/api/user'

const _import = require('@/router/_import_' + process.env.NODE_ENV) //获取组件的方法
var getRouter //用来获取后台拿到的路由
let asyncRoutes = [
  {
    path: '/product',
    component: Layout,
    redirect: '/product/product',
    alwaysShow: true, // will always show the root menu
    name: 'Product',
    meta: {
      title: '商品管理',
      icon: 'lock',
      roles: ['merchant']
    },
    children: [
      {
        path: '/product1',
        component: () => import('@/views/product/product'),
        name: 'Product',
        meta: {
          title: '商品管理',
          roles: ['merchant']

        }
      },
      {
        path: '/category',
        component: () => import('@/views/product/category'),
        name: 'Category',
        meta: {
          title: '商品分类',
          roles: ['merchant']
        }
      }
    ]
  }

]
let fakeRouter = {
  'router': [{
    'path': '',
    'component': 'Layout',
    'redirect': 'dashboard',
    'children': [{
      'path': 'dashboard',
      'component': 'dashboard/index',
      'meta': {
        'title': 'hhah',
        'icon': 'dashboard'
      }
    }]
  },
    {
      'path': '/example',
      'component': 'Layout',
      'redirect': '/example/table',
      'name': 'Example',
      'meta': {
        'title': '111',
        'icon': 'example'
      },
      'children': [{
        'path': 'table',
        'name': 'Table',
        'component': 'table/index',
        'meta': {
          'title': '11',
          'icon': 'table'
        }
      },
        {
          'path': 'tree',
          'name': 'Tree',
          'component': 'tree/index',
          'meta': {
            'title': '树形121菜单',
            'icon': 'tree'
          }
        }
      ]
    },
    {
      'path': '/form',
      'component': 'Layout',
      'children': [{
        'path': 'index',
        'name': 'Form',
        'component': 'form/index',
        'meta': {
          'title': '2131112',
          'icon': 'form'
        }
      }]
    },
    {
      'path': '*',
      'redirect': '/404',
      'hidden': true
    }
  ]

}
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
// function hasPermission(roles, route) {
//   if (route.meta && route.meta.roles) {
//     return roles.some(role => route.meta.roles.includes(role.role))
//   } else {
//     return true
//   }
// }

/**
 * Filter asynchronous routing tables by recursion
 * @param routes 路由
 * @param roles 用户查询到的权限
 */
// export function filterAsyncRoutes(routes, roles) {
//   const res = []
//   routes.forEach(route => {
//     const tmp = { ...route }
//     if (hasPermission(roles, tmp)) {
//       if (tmp.children) {
//         tmp.children = filterAsyncRoutes(tmp.children, roles)
//       }
//       res.push(tmp)
//     }
//   })
//   return res
// }

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

async function getRoles() {
  await getInfo().then(res => {
    getRouter = filterAsyncRouter(res.dataMap.permissionMenus)

  })
  return getRouter

}

const actions = {
  generateRoutes: function({ commit }, roles) {
    return new Promise(async resolve => {
      console.log(asyncRoutes)
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = await getRoles()

        // accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}


function filterAsyncRouter(asyncRouterMap) { //遍历后台传来的路由字符串，转换为组件对象
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.component) {
      if (route.component === 'Layout') { //Layout组件特殊处理
        route.component = Layout
      } else {
        route.component = _import(route.component)
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })

  return accessedRouters
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
